<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Exception\ApiServerException;
use App\Exception\HttpServerException;
use App\Exception\ThirdPartyException;
use App\Exception\UnifyOauthException;
use App\Exception\ValidateException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\ResponseInterface as Respon2seInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Inject
     * @var Respon2seInterface
     */
    protected $response;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        switch (true) {
            case ($throwable instanceof ValidateException):
                $code = 300;
                return $response->withStatus(200)
                    ->withHeader('Content-Type', 'application/json')
                    ->withBody(new SwooleStream(json_encode(error($throwable->getMessage(), $code), JSON_UNESCAPED_UNICODE)));
            case ($throwable instanceof UnifyOauthException):
                $code = 301;
                break;
            case ($throwable instanceof ThirdPartyException):
                $code = 600;
                break;
            case ($throwable instanceof HttpServerException):
                $code = 400;
                $returnRes = [
                    'code' => $code,
                    'msg' =>  $throwable->getMessage(),
                    'data' => !empty($data['url'])?$data['url']:'/',
                    'wait' => !empty($data['wait'])?$data['wait']:3,
                ];
                $param = base64_encode(json_encode($returnRes));
                return $this->response->redirect('/jump?param='.$param);
                break;
            case ($throwable instanceof ApiServerException):
                $code = 400;
                return $response->withStatus(200)
                    ->withHeader('Content-Type', 'application/json')
                    ->withBody(new SwooleStream(json_encode(error($throwable->getMessage(), $code), JSON_UNESCAPED_UNICODE)));
            default:
                $code = 500;
                break;
        }
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        return $response->withHeader("Server", "Hyperf")->withStatus($code)->withBody(new SwooleStream('Internal Server Error.'));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
